/* Connect to Redis 连接到redis服务器 */
var Redis = require('ioredis');
var redis = new Redis({
  port: 6379, // Redis port
  host: '127.0.0.1', // Redis host
  family: 4, // 4 (IPv4) or 6 (IPv6)
  password: '',
  db: 0
});

/* basic usage 基础用法 */
redis.set('foo', 'bar');
redis.get('foo').then(result => {
  // 这里必须用.then来接收返回的结果，不使用.then获取到的result是null
  console.log(result);
});
redis.sadd('set', 1, 2, 7, 9);
// redis.sadd('set', [1, 3, 5, 7, 9]);

/* publish/subscribe 发布和订阅 */
var pub = new Redis();
redis.subscribe('news', 'music').then(count => {
  // 订阅news和music两个频道
  // `count` 代表当前订阅的序号
  pub.publish('news', 'Hello world!');
  pub.publish('music', 'Hello again!');
});

redis.on('message', (channel, message) => {
  // 这里监听news和music两个频道，不能用.then来接收返回的结果（会报错）
  // Receive message Hello world! from channel news
  // Receive message Hello again! from channel music
  console.log('Receive message %s from channel %s', message, channel);
});

redis.on('messageBuffer', (channel, message) => {
  // messageBuffer事件,返回buffer替代字符串
  // Both `channel` and `message` are buffers.
  console.log('Receive messageBuffer %s from channel %s', message, channel);
});

/* Pipelining 管道 */
// 若此前已有redis链接，此处需重新建立一个redis链接
var redisPipeline = new Redis();

var pipeline = redisPipeline.pipeline();
pipeline.set('foo', 'bar');
pipeline.del('cc');
pipeline.exec(results => {
  console.log(results);
});

// 链式调用命令
redisPipeline.pipeline().set('foo', 'bar').del('cc').exec(results => {
  console.log(results);
});

// `exec` 也是返回的promise
var promise = redisPipeline.pipeline().set('foo', 'bar').get('foo').exec();
promise.then(result => {
  console.log(result);
  console.log(result[1][1]);
  // result === [[null, 'OK'], [null, 'bar']]
});

// 每个链式命令都可以有一个回调 -> pipeline不支持.then方法，因此获取到的result都是null -> 不建议在 nodejs里使用此api
redisPipeline.pipeline().set('foo', 'bar').get('foo', result => {
  console.log(result);
  // result === 'bar'
}).exec(result => {
  console.log(result);
  // result[1][1] === 'bar'
});

const length = redis.pipeline().set('foo', 'bar').get('foo').length;
console.log(length);
